import { random } from 'lodash-es'
import * as spritejs from 'spritejs'
import { keyDowned } from '.'
import carImg from '../assets/car.png'
import { isHitWall } from './isHitWall'
import { setSelectedCar } from './selectedCar'
import { carEnterPark, updateEnterScreen, resetLeaveScreen, carInOutParkSpace } from '../screens'
import { leaveDoor } from './doors'
const { Scene, Sprite, Polyline, Rect, Label, Layer, Group, Block, Path } =
    spritejs

export const cars: Car[] = []

// 车子的图片
const sourceRects = [
    [40, 30, 230, 520],
    [330, 30, 230, 520],
    [590, 30, 230, 520],
    [860, 15, 230, 520],
    [1150, 15, 230, 520],
    [1415, 15, 230, 520],
]

const randomGetSourceRect = () => {
    const index = random(0, sourceRects.length - 1)
    return sourceRects[index]
}

/**
 * 汽车类
 */
export class Car {
    id // id
    layer // layer
    sprite // 车子
    text // 文字
    options // 配置
    group // 车子和文字的组合
    parkSpaceId // 停车位id,如果有值，说明停在了车位上
    inPark // 是否在停车场内
    isSelected // 是否被选中

    constructor(layer, id, options) {
        this.id = id
        this.layer = layer
        this.parkSpaceId = options.parkSpaceId || undefined
        this.inPark = false
        this.options = options
        const x = options.x !== undefined ? options.x : 100
        const y = options.y !== undefined ? options.y : 520
        this.group = new Group({
            pos: [x, y],
            size: [80, 160],
            anchor: [0.5, 0.5],
        })
        this.sprite = new Sprite({
            id: 'car1',
            anchor: [0.5, 0.5],
            size: [80, 160],
            pos: [0, 0],
            texture: carImg,
            sourceRect: randomGetSourceRect(),
        })
        // 创建一个文本
        this.text = new Label({
            pos: [0, -10],
            text: this.id,
            fontSize: 12,
            textAlign: 'center',
            fillColor: '#000',
            anchor: [0.5, 0.5],
            size: [80, 160],
        })
        this.init()
        if (options.clickable !== false) {
            this.group.addEventListener('click', () => {
                console.log('点击了车子')
                setSelectedCar(this)
            })
        }
        cars.push(this)
    }

    init() {
        // 添加到layer
        this.group.append(this.sprite)
        this.group.append(this.text)
        this.layer.append(this.group)
    }

    ArrowUp() {
        // 获取角度
        const rotate = this.group.attr('rotate')
        // 获取弧度
        const radian = (rotate * Math.PI) / 180
        // 获取x轴偏移量
        const offsetX = Math.sin(radian) * 3
        // 获取y轴偏移量
        const offsetY = Math.cos(radian) * 3
        const newX = this.group.attr('x') + offsetX
        const newY = this.group.attr('y') - offsetY
        if (isHitWall(this.group, offsetX, 'ArrowUp')) return
        this.group.attr('x', newX)
        this.group.attr('y', newY)
        if (!this.inPark && newX > 300) {
            this.inPark = true
            carEnterPark(this.id)
            console.log('进入停车场')
        } else if (this.inPark && newX < 300) {
            this.inPark = false
            resetLeaveScreen()
            console.log('离开停车场')
            setTimeout(() => {
                leaveDoor.close()
            }, 1000)
        }
    }

    ArrowDown() {
        // 获取角度
        const rotate = this.group.attr('rotate')
        // 获取弧度
        const radian = (rotate * Math.PI) / 180
        // 获取x轴偏移量
        const offsetX = Math.sin(radian) * 3
        // 获取y轴偏移量
        const offsetY = Math.cos(radian) * 3
        const newX = this.group.attr('x') - offsetX
        const newY = this.group.attr('y') + offsetY
        if (isHitWall(this.group, offsetX, 'ArrowDown')) return
        this.group.attr('x', newX)
        this.group.attr('y', newY)
    }

    ArrowLeft() {
        if (!keyDowned.ArrowUp && !keyDowned.ArrowDown) return
        // 是否在倒车
        const isBack = keyDowned.ArrowDown
        if (isBack) {
            this.group.attr('rotate', (r) => r + 2)
        } else {
            this.group.attr('rotate', (r) => r - 2)
        }
    }

    ArrowRight() {
        if (!keyDowned.ArrowUp && !keyDowned.ArrowDown) return
        // 是否在倒车
        const isBack = keyDowned.ArrowDown
        if (isBack) {
            this.group.attr('rotate', (r) => r - 2)
        } else {
            this.group.attr('rotate', (r) => r + 2)
        }
    }

    // 判断是否在某个区域内
    isIn(block: InstanceType<typeof Block> | InstanceType<typeof Path>) {
        const carInfo = this.group.getBoundingClientRect()
        const blockInfo = block.getBoundingClientRect()
        // 判断是否在区域内
        const isInFlag =
            carInfo.left > blockInfo.left - 10 &&
            carInfo.right < blockInfo.right + 10 &&
            carInfo.top > blockInfo.top - 10 &&
            carInfo.bottom < blockInfo.bottom + 10

        // console.log(isInFlag)
        return isInFlag
    }

    // 设置停车位id
    setParkSpaceId(id: string | undefined, parkSpaceInfo: any) {
        console.log(this.id + '停在了' + id)
        carInOutParkSpace(parkSpaceInfo.id, id !== undefined)
        this.parkSpaceId = id
    }

    // 设置选中状态
    setSelected(flag: boolean) {
        this.isSelected = flag
        if (flag) {
            this.text.attr('fillColor', '#409eff')
        } else {
            this.text.attr('fillColor', '#000')
        }
    }

    // 删除
    remove() {
        this.group.remove()
        const index = cars.findIndex((item) => item.id === this.id)
        cars.splice(index, 1)
    }
}
